import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import type { User } from '../types'

export const useSelection = (isMultiple = false, maxSelection = 50) => {
  // 已选择的用户
  const selectedUsers = ref<User[]>([])

  // 初始化已选择的用户
  const initSelectedUsers = (users: User[]) => {
    if (!users || !Array.isArray(users)) return

    // 多选模式下，检查最大选择数量
    if (isMultiple && maxSelection > 0 && users.length > maxSelection) {
      ElMessage.warning(`最多只能选择${maxSelection}个用户`)
      selectedUsers.value = users.slice(0, maxSelection)
    } else {
      selectedUsers.value = [...users]
    }
  }

  // Handles selection changes from the table (individual ticks or header select-all page)
  const updateSelectionFromTable = (currentPageTableSelection: User[], allUsersOnCurrentPage: User[]) => {
    if (!isMultiple) {
      selectedUsers.value = currentPageTableSelection.length > 0 ? [currentPageTableSelection.at(-1)!] : []
      return
    }

    // 2. Get users selected previously, EXCLUDING any users that are visible on the current page.
    //    This preserves selections from other pages.
    const selectedFromOtherPages = selectedUsers.value.filter(
      (existingUser) => !allUsersOnCurrentPage.some((userOnPage) => userOnPage.id === existingUser.id)
    )

    // 3. Combine users from other pages with the users selected on the current page.
    let combinedSelection = [...selectedFromOtherPages]
    currentPageTableSelection.forEach((user) => {
      // Add user from current page selection if not already included (shouldn't be, due to step 2)
      if (!combinedSelection.some((u) => u.id === user.id)) {
        combinedSelection.push(user)
      }
    })

    // Optional: Deduplicate just in case - although the logic above should prevent duplicates.
    const uniqueIds = new Set<string>()
    combinedSelection = combinedSelection.filter((user) => {
      if (uniqueIds.has(user.id)) return false
      uniqueIds.add(user.id)
      return true
    })

    // 4. Apply Max Selection Limit
    if (maxSelection > 0 && combinedSelection.length > maxSelection) {
      ElMessage.warning(`最多只能选择${maxSelection}个用户`)
      // Simply keep the first N users based on the combined list order.
      combinedSelection = combinedSelection.slice(0, maxSelection)
    }

    // 5. Assign the final array to the ref to trigger reactivity.
    selectedUsers.value = combinedSelection
  }

  // Adds all users from the current page to the global selection
  const addCurrentPageUsersToSelection = (pageUsers: User[]) => {
    if (!isMultiple) return // Should not be called in single select mode

    const usersToAdd = pageUsers.filter((pu) => !selectedUsers.value.some((su) => su.id === pu.id))
    let newSelection = [...selectedUsers.value, ...usersToAdd]

    if (maxSelection > 0 && newSelection.length > maxSelection) {
      const spaceAvailable = maxSelection - selectedUsers.value.length
      if (spaceAvailable > 0 && usersToAdd.length > spaceAvailable) {
        ElMessage.warning(`已达选择上限，仅添加部分用户`)
        newSelection = [...selectedUsers.value, ...usersToAdd.slice(0, spaceAvailable)]
      } else if (spaceAvailable <= 0) {
        ElMessage.warning(`已达选择上限，无法添加更多用户`)
        return // Do not change selection if no space
      }
      // If newSelection still exceeds, it implies selectedUsers.value itself was full or near full.
      // The warning about adding only some, or none, covers this.
    }
    selectedUsers.value = newSelection
    // Re-check and slice if, due to logic, it still somehow exceeded (shouldn't with above)
    if (maxSelection > 0 && selectedUsers.value.length > maxSelection) {
      selectedUsers.value = selectedUsers.value.slice(0, maxSelection)
    }
  }

  // 移除用户
  const removeUser = (user: User) => {
    const index = selectedUsers.value.findIndex((item) => item.id === user.id)
    if (index !== -1) {
      selectedUsers.value.splice(index, 1)
    }
  }

  // 清空选择
  const clearSelection = () => {
    selectedUsers.value = []
  }

  return {
    selectedUsers,
    initSelectedUsers,
    updateSelectionFromTable,
    addCurrentPageUsersToSelection,
    removeUser,
    clearSelection,
  }
}
